package morning.cat.curator.generator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.CountDownLatch;


/**
 * XXX
 *
 * @author mengzhang6
 * @date 2018/11/22 13:51
 */
public class OrderNoGenerator {


    static String lock_path = "/curator_recipes_lock_path";
    static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("127.0.0.1:2181")
            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();


    public static void main(String[] args) throws Exception {


        client.start();
        final InterProcessMutex lock = new InterProcessMutex(client, lock_path);
        final CountDownLatch down = new CountDownLatch(1);
        for (int i = 0; i < 30; i++) {


            new Thread(new Runnable() {
                public void run() {
                    try {
                        down.await();
                        lock.acquire();
                        System.out.println("生成的订单号为：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss-S")));
                        Thread.sleep(1);
                    } catch (Exception e) {
                        System.out.println(e);
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
            }).start();


        }
        down.countDown();
    }


}
